#include "StdAfx.h"
#include <Layer>
#include <LayerManager>

LayerManager::LayerManager(QSize size, QObject *parent)
	: QObject(parent)
	, m_size(size)
{
	m_mainLayer = new Layer(this, "Main Layer", true, this);
}

LayerManager::~LayerManager()
{

}

QPointer<Layer> LayerManager::mainLayer() const
{
	Q_ASSERT(m_mainLayer);
	return m_mainLayer;
}

QPointer<Layer> LayerManager::addLayer( const QString& strLayerName /*= QString()*/ )
{
	QString name = strLayerName;
	if(name.isEmpty())
	{
		name = QString("Layer%1").arg(m_layers.size() + 1);
	}

	QPointer<Layer> newLayer = new Layer(this, name);
	
	if(newLayer)
	{
		m_layers << newLayer;
		emit layerAdded(newLayer);
	}

	return newLayer;
}

QPointer<Layer> LayerManager::layer( const QString& name ) const
{
	QPointer<Layer> layer;
	QList<QPointer<Layer> >::const_iterator iterLayer = m_layers.begin();

	while(iterLayer != m_layers.end())
	{
		if((*iterLayer)->name() == name)
		{
			layer = *iterLayer;
			break;
		}

		++iterLayer;
	}

	return layer;
}

unsigned int LayerManager::layerCount() const
{
	return m_layers.count();
}

bool LayerManager::removeLayer( const QString& name )
{
	bool result = false;

	QPointer<Layer> layerToRemove = layer(name);

	if(layerToRemove)
	{
		m_layers.removeOne(layerToRemove);
		emit layerRemoved(layerToRemove);
		result = true;
	}

	return result;
}

void LayerManager::paint( QPainter& painter )
{
	Q_ASSERT(m_mainLayer);
	m_mainLayer->paint(painter);

	foreach(QPointer<Layer> layer, m_layers)
	{
		layer->paint(painter);
	}
}

const QSize LayerManager::size() const
{
	return m_size;
}
